function plot_data(data_mat,countries,timeline,title_string,legends,xlimits)
% function plot_data(data_mat,countries,timeline,title_string,legends,xlimits)
% plot dataseries
% Inputs:
%       data_mat        [T by ncountries by nvars] matrix     data matrix 
%       countries       [1 by ncountries] cell array country_names
%       timeline        [N by 1] vector     timeline vector with format 2001.25
%                                               for 2001Q2 
%       title_string    string            Figure title

% Copyright (C) 2019-2023 Benjamin Born, Francesco D'Ascanio, Gernot J. Mueller, Johannes Pfeifer
%
% This is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% It is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
% 
% For a copy of the GNU General Public License,
% see <http://www.gnu.org/licenses/>.


n_countries=size(data_mat,2);
n_vars=size(data_mat,3);

n_figures=ceil(n_countries/12);

styles={'-','--','-.'};
for fig_iter=1:n_figures
    f=figure('Name',[title_string, num2str(fig_iter)]);
    set(f,'PaperType','a4','PaperPositionMode','manual','PaperUnits','centimeters','PaperPosition',[1,1,21,24],'renderer', 'painters');
    for country_iter=1:12
        subplot(4,3,country_iter);
        for var_iter=1:n_vars
            hh(var_iter)=plot(timeline,data_mat(:,(fig_iter-1)*12+country_iter,var_iter),'LineWidth',1,'LineStyle',styles{1,1+mod(var_iter-1,3)});
            hold on            
            title(countries{1,(fig_iter-1)*12+country_iter});
        end
        if nargin==6
            xlim(xlimits)
        end
        hline(0);
        if (fig_iter-1)*12+country_iter ==n_countries
            print(['Figures/',[title_string, num2str(fig_iter)]],'-dpdf')
            print(['Figures/',[title_string, num2str(fig_iter)]],'-depsc')
            if nargin>=5 && ~isempty(legends)
                legend(hh,legends)
                legend('boxoff')
            end
            return
        end
    end
    if nargin>=5 && ~isempty(legends)
        legend(hh,legends,'Location','NorthWest')
        legend('boxoff')
    end
    print(['Figures/',[title_string, num2str(fig_iter)]],'-dpdf')
    print(['Figures/',[title_string, num2str(fig_iter)]],'-depsc')
end
